<template>
  <ele-page>
    <search @search="reload" />
    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="roleId"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        highlight-current-row
        :where="defaultWhere"
        show-summary
        :summary-method="getSummaries"
        border
      >
        <template #toolbar="{}">
          <el-button type="success" @click="exportExcel" :icon="DocumentCopy">
            导出表格
          </el-button>
          <span style="margin-left: 8px">总计：{{ totalAmount }}元</span>
        </template>
        <template #user_name="{ row }">
          <span class="pointer blue" @click="showStudentDetail(row.user_id)">
            {{ row.user_name }}
          </span>
          <span
            v-if="row.share_user_id > 0"
            class="pointer red"
            @click="showStudentDetail(row.share_user_id)"
          >
            （{{ row.share_user }}）
          </span>
        </template>
        <template #action="{ row }">
          <el-link type="danger" :underline="false" @click="handdleRefund(row)">
            退款
          </el-link>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 学生详情 -->
    <detail v-model="showDetail" :student-id="currentId" @done="reload" />
  </ele-page>
</template>

<script setup>
  import { ref, computed } from 'vue';
  import { pageMallTrade, exportMallTradeList, refundTrade } from '@/api/mall';
  import { EleMessage } from 'ele-admin-plus/es';
  import { DocumentCopy } from '@element-plus/icons-vue';
  import Search from './components/search.vue';
  import Detail from '@/views/student/components/detail.vue';
  import { accAdd } from '@/utils/my-common';
  import { ElMessageBox } from 'element-plus/es';

  /** 表格实例 */
  const tableRef = ref(null);

  const totalAmount = ref(0);

  /** 表格列配置 */
  const columns = computed(() => {
    const cols = [
      {
        prop: 'id',
        label: 'ID',
        width: 80,
        align: 'center'
      },
      {
        prop: 'goods_title',
        label: '订单商品名称'
      },
      {
        prop: 'goods_remark',
        label: '备注',
        width: 150
      },
      {
        prop: 'tenant',
        label: '来源',
        width: 100
      },
      {
        slot: 'user_name',
        label: '购买会员',
        width: 180
      },
      {
        prop: 'tel',
        label: '电话',
        width: 130
      },
      {
        prop: 'goods_price',
        label: '商品价格',
        width: 100
      },
      {
        prop: 'valid_code',
        label: '核销码',
        width: 110
      }
    ];
    if (status.value == 'refunded') {
      cols.push({
        prop: 'refund_judge_time',
        label: '退款时间',
        width: 160
      });
    } else {
      cols.push({
        prop: 'create_time',
        label: '购买时间',
        width: 160
      });
    }
    cols.push({
      prop: 'status',
      label: '状态',
      width: 200
    });
    if (status.value == 'wating') {
      cols.push({
        slot: 'action',
        label: '操作',
        align: 'center',
        width: 70
      });
    }

    return cols;
  });

  /** 表格选中数据 */
  const selections = ref([]);

  /** 表格数据源 */
  const datasource = async ({ page, where, orders, limit }) => {
    const result = await pageMallTrade({
      ...where,
      ...orders,
      page,
      limit
    });
    console.log('result:', result);
    totalAmount.value = result.totalAmount;

    return result;
  };

  const defaultWhere = ref({
    status: '全部',
    create_time: '',
    valid_time: '',
    realname: '',
    tel: '',
    title: ''
  });

  const status = ref('全部');

  /** 搜索 */
  const reload = (where) => {
    status.value = where ? where.status : '全部';
    selections.value = [];
    tableRef.value?.reload?.({ page: 1, where });
  };

  /** 导出表格 */
  const exportExcel = () => {
    const loading = EleMessage.loading('请求中..');
    tableRef.value?.fetch(({ where }) => {
      // 方法的参数与数据源的完全一致
      // 请求查询全部接口
      console.log(where);
      var requestData = where;
      requestData.limit = 99999999;
      requestData.page = 1;

      exportMallTradeList(requestData)
        .then((res) => {
          loading.close();
          window.open(res);
        })
        .catch(() => {
          loading.close();
        });
    });
  };

  /** 是否显示编辑弹窗 */
  const currentId = ref(0);
  const showDetail = ref(false);
  /** 学生详情 */
  const showStudentDetail = (id) => {
    currentId.value = id ?? 0;
    showDetail.value = true;
  };

  const getSummaries = (param) => {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = '本页统计';
        return;
      }
      const values = data.map((item) => Number(item[column.property]));
      if (index === 5) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return accAdd(prev, curr);
          } else {
            return prev;
          }
        }, 0);
        sums[index] += ' 元';
      } else {
        sums[index] = '/';
      }
    });

    return sums;
  };

  /** 删除单个 */
  const handdleRefund = (row) => {
    ElMessageBox.confirm(
      '确定要将“' + row.realname + '”的“' + row.goods_title + '”退款吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        const loading = EleMessage.loading('请求中..');
        refundTrade({ trade_id: row.id, pay_record_id: row.pay_record_id })
          .then((msg) => {
            loading.close();
            EleMessage.success(msg);
            reload();
          })
          .catch((e) => {
            loading.close();
            EleMessage.error(e.message);
          });
      })
      .catch(() => {});
  };
</script>

<script>
  export default {
    name: 'SystemRole'
  };
</script>
